﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Text;


namespace FormatTest
{
    public class DecodeH264
    {
        public static nal_unit vnal_unit = null;

        public static StringBuilder p_bytes = null;

        public static string nal_header = null;

        public static seq_parameter_set_rbsp vseq_parameter_set_rbsp = null;

        public static pic_parameter_set_rbsp vpic_parameter_set_rbsp = null;

        public static int prevPicOrderCntMsb = 0;

        public static int prevPicOrderCntLsb = 0;

        public static slice_header vslice_header = null;

        static void Main(string[] args)
        {
            int step = 4096, index = 0;
            using (FileStream fs = File.OpenRead(@"E:\H264\test.h264"))
            {
                var bytes = new byte[step];
                while (index < fs.Length)
                {
                    fs.Read(bytes, index, step);
                    Analysis(bytes);
                    index += step;
                }
            }
        }



        static void Analysis(byte[] bytes)
        {
            for (var i = 0; i < bytes.Length; i++)
            {
                if (bytes[i] == 0x00 && bytes[i + 1] == 0x00 && bytes[i + 2] == 0x00 && bytes[i + 3] == 0x01)
                {
                    if (p_bytes != null)
                    {
                        vnal_unit = new nal_unit(nal_header);
                        var str_bytes = Common.RetrieveBytes(p_bytes.ToString());
                        if (vnal_unit.nal_unit_type == 7)
                        {
                            vseq_parameter_set_rbsp = new seq_parameter_set_rbsp(str_bytes);
                        }
                        else if (vnal_unit.nal_unit_type == 8)
                        {
                            vpic_parameter_set_rbsp = new pic_parameter_set_rbsp(str_bytes);
                        }
                        else if (vnal_unit.nal_unit_type >= 1 && vnal_unit.nal_unit_type <= 5)
                        {
                            if (vseq_parameter_set_rbsp.pic_order_cnt_type == 0)
                            {
                                //nal_unit_type==5 then this is IDR picture
                                if (vnal_unit.nal_unit_type == 5)
                                {
                                    prevPicOrderCntMsb = 0;
                                    prevPicOrderCntLsb = 0;
                                }
                                else //not IDR picture
                                {

                                }
                            }
                        }
                    }
                    p_bytes = new StringBuilder();
                    nal_header = Convert.ToString(bytes[i + 4], 2).PadLeft(8, '0');
                    i = i + 5;
                }
                p_bytes.Append(Convert.ToString(bytes[i], 2).PadLeft(8, '0'));
            }
        }

    }
}
